<template>
	<view class="backpanle">
	    <view>发布商业信息</view>
		<view v-if="picpath.length>0">
			<scroll-view class="scroll-view_H" scroll-x="true" scroll-left="120">
				<view v-if="picpath.length>0" class="scroll-view-item_H" v-for="(pic, index) in picpath" :key="index">
				<view class="photos-box">	<image class="photos" :src="pic" mode="aspectFill"></image></view>
			</view>
			
			</scroll-view>
		</view>
		<view v-else class="no-pic-tip">请添加店面图片(最多9张)</view>
		<view class="">	<button style="width: 50%;" type="primary"  @click="chooseimg">{{addpice()}}</button></view>
	

		<view class="input">
			<view class="input-item">
				<text>公司/店铺名称：</text>
				<input type="text" class="inputTxt" v-model="name" />
			</view>
			<view class="input-item">
				<text>地址：</text>
				<input type="text" class="inputTxt" v-model="address" placeholder="" />
			</view>
			<view class="input-item">
				<text>商业类型：</text>
				<picker mode="selector" :range="pickkeytag" @change="bindUnitChange">
					<view>{{ keytags }}</view>
				</picker>
			</view>
			<view class="input-item">
				<text>营业时间：</text>
				<input type="text" class="inputTxt" v-model="opentime_today" placeholder="营业时间段" />
			</view>
			<view class="input-item">
				<text>联系电话：</text>
				<input type="number" class="inputTxt" v-model="tel" placeholder="请输入电话号码" />
			</view>
			<view class="input-item">
				<text>详情：</text>
				<textarea v-model="description" placeholder="店铺或服务详细描述" class="inputTxt" />
			</view>
		</view>
         <view class="btn-box"><view class="btn" @click="publishInfo">发布信息</view></view>
		
	</view>
</template>

<script>
import {sendMsg} from '../../methods/msgSend.js';
const db = uniCloud.databaseForJQL();
import { shopIcon, keytag, keytagObj } from '../../utils/shopIcon.js';

export default {
	data() {
		return {
			user: null,
			location: {},
			pickkeytag: this.keytag(),
			name: '',
			keytags: '请选择',
			opentime_today: '',
			address: '',
			tel: '',
			picpath: [],
			isSubmitting: false,
			photos: [],
			description: '',
			unitIndex: null
		};
	},
	computed:{
		storeDate(){
		return	this.$store.state.msg
			}
	},
	
	onLoad(e) {
		if(e){
				this.keytags = e.key;
		}

	},

	methods: {
		keytag,
		
		addpice(){
			if(this.picpath.length===0){
				return "添加图片"
			}else if(this.picpath.length>0&&this.picpath.length<10){
				return `还能添加${9-this.picpath.length}张`
			}
		},
		bindUnitChange(e) {
			this.unitIndex = e.detail.value;
			this.keytags = this.pickkeytag[this.unitIndex];
			
		},
	chooseimg() {
	    if (this.picpath.length >= 9) {
	        uni.showToast({
	            title: '已达9张图片上限'
	        });
	        return;
	    }
	    uni.chooseImage({
	        count: 9,
	        success: (res) => {
	            if (res.tempFilePaths.length + this.picpath.length > 9) {
	                uni.showModal({
	                    title: '数量超限',
	                    content: `最多只能再加${9 - this.picpath.length}张图片`,
	                    success: (modalRes) => {
	                        if (modalRes.confirm) {
	                            // 这里可以添加跳转到图片管理页面的逻辑
	                        }
	                    }
	                });
	            } else {
	                this.picpath = [...this.picpath, ...res.tempFilePaths];
	            }
	            console.log('图片地址', this.picpath);
	        },
	        fail: (err) => {
	            console.error('图片选择失败', err);
	            if (err.errCode === 'chooseImage:fail cancel') {
	                uni.showToast({
	                    title: '用户取消选择图片',
	                    icon: 'none'
	                });
	            } else {
	                uni.showToast({
	                    title: '图片选择失败，请重试',
	                    icon: 'none'
	                });
	            }
	        }
	    });
	},
	async publishInfo() {
	    // 构造位置对象
	    const location = new db.Geo.Point(this.storeDate.location.longitude, this.storeDate. location.latitude);
	
	    // 防止重复提交
	    if (this.isSubmitting) return;
	    this.isSubmitting = true;
	
	    try {
	        // 表单验证
	        if (!this.name.trim()) {
	            uni.showToast({ title: '填写公司商铺名', icon: 'none' });
	            return;
	        }
	        if (!this.address.trim()) {
	            uni.showToast({ title: '请填写地址', icon: 'none' });
	            return;
	        }
	        if (this.unitIndex === null) {
	            uni.showToast({ title: '选择商业类型', icon: 'none' });
	            return;
	        }
	
	        // 图片上传
	        uni.showLoading({ title: '上传图片中...' });
	        const uploadedPhotos = [];
	        for (const picpath of this.picpath) {
	            try {
	                const picName = new Date().getTime();
	                const sanitizedUserTel = this.storeDate.user.userTel.replace(/[^a-zA-Z0-9]/g, '');
	                const uploadRes = await uniCloud.uploadFile({
	                    cloudPath: `/sendshop/${picName}${sanitizedUserTel}.jpg`,
	                    filePath: picpath
	                });
	                const urlRes = await uniCloud.getTempFileURL({ fileList: [uploadRes.fileID] });
	                const urlresObj = { url: urlRes.fileList[0].tempFileURL };
	                uploadedPhotos.push(urlresObj);
	            } catch (uploadError) {
	                console.error('图片上传失败:', uploadError);
	                uni.showToast({ title: '图片上传失败，请重试', icon: 'none' });
	                // 可以考虑在这里添加重试逻辑或者记录失败的图片路径
	            }
	        }
	
	        // 构造数据
	        const sendshopId = `${this.storeDate.user.userId}${new Date().getTime()}`;
	        const upData = {
	            sendshopId: sendshopId,
	            title: this.name,
	            tel: this.tel,
	            address: this.address,
	            category: this.keytags,
	            location: location,
	            photos: uploadedPhotos,
	            sendTime: new Date().getTime(),
	            sendUserId: this.storeDate.user.userId,
	            business: {
	                tel: this.tel,
	                opentime_today: this.opentime_today,
	                keytag: this.keytags
	            }
	        };
	
	        // 数据库插入
	        const sendshopData = await db.collection('sendshop').add(upData);
	        if (sendshopData.id) {
	            const toTarget = {
	                targetType: '1', //1，公聊，2，群聊，3，私聊
	                targetName: '邻里周边',
	                targetId: []
	            };
	           const msg = {
	               sendshopId: sendshopId
	           };
	           const messageType = 5;
	           await sendMsg(messageType, toTarget, msg,this.storeDate);
	
	            // 清空表单
	            Object.assign(this.$data, this.$options.data.call(this));
	            uni.showToast({ title: '发布成功' });
	            // 跳转逻辑...
	            uni.navigateBack();
	            console.log('数据插入成功，sendshopId:', sendshopData.id); // 添加日志记录
	        }
	    } catch (e) {
	        console.error('发布失败:', e);
	        uni.showToast({ title: '发布失败，请重试', icon: 'none' });
	    } finally {
	        this.isSubmitting = false;
	        uni.hideLoading();
	    }
	}
	}
};
</script>

<style lang="scss" scoped>
.backpanle {
	display: flex;
	flex-direction: column;
	width: 750rpx;
	padding: 20rpx;
	margin-bottom: 130rpx;
	background-color: #eaeaea;
}
.photos-box{
	display: flex;
	align-items: center;
	justify-content: center;
	width: 200rpx;
	margin: 20rpx;
	height: 250rpx;
	background-color: #666;
	border-radius: 5rpx;
}

.photos {
	width: 180rpx;
	height: 230rpx;
}

.input {
	margin-top: 40rpx;

	.input-item {
		padding-left: 25rpx;
		display: flex;
		flex-direction: column;
		margin-bottom: 40rpx;
		font-size: 32rpx;
       font-weight: 500;
		margin-bottom: 15rpx;
	

		.inputTxt,
		picker {
			width: 100%;
			min-height: 80rpx;
			padding: 20rpx;
			border: 1rpx solid #eee;
			border-radius: 8rpx;
			font-size: 28rpx;
			background-color: #f9f9f9;
			box-sizing: border-box;
		}

		textarea {
			height: 200rpx;
		}
	}
}

.btn {
    width: 80%;
	height: 80rpx;
	background-color: #007aff;
	color: #fff;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}
.no-pic-tip {
	display: flex;
	align-items: center;
	justify-content: center;
		width: 750rpx;
		height: 300rpx;
		color: #999;
		font-size: 18px;
	}

.scroll-view_H {
	white-space: nowrap;
	margin-top: 20rpx;
	width: 100%;
}
.scroll-view-item_H {
	display: inline-block;

	height: 300rpx;
	
}
.btn-box{
	display: flex;
	position: fixed;
	bottom: 0;
	left: 0;
	background-color: white;
	align-items: center;
	justify-content: center;
	width: 750rpx;
	height: 120rpx;
}
</style>
